package cn.chenxinjie.hrm.util.exception;

import cn.chenxinjie.hrm.util.AjaxResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

/**
 * 全局异常处理,处理所有的Controller
 * @author 陈鑫杰
 * @date 2022/3/9 18:27
 */
@RestControllerAdvice
public class HrmGlobalExceptionHandler {
    // 捕获所有的运行时异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleRuntimeException(RuntimeException e){
        return AjaxResult.me().setSuccess(false).setMessage("全局异常处理:" + e.getMessage());
    }

    // 捕获所有的业务异常
    @ExceptionHandler(HrmBusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleBusinessException(HrmBusinessException e){
        return AjaxResult.me().setSuccess(false).setMessage("业务异常:" + e.getMessage());
    }

    /**
     * 对捕获的jsr303异常进行消息格式的处理
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleBusinessException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        List<FieldError> errors = result.getFieldErrors();
        HashMap<String, Object> map = new HashMap<>();
        errors.forEach(fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return AjaxResult.me().setErrCode(HrmBusinessErrCode.BUSINESS_FAIL).setSuccess(false).setMessage(map.toString());
    }

}
